<template>
  <div id="main"></div>
</template>

<script setup lang="ts">
import { Application, Assets, ICanvas, Sprite } from "pixijs";
import { onMounted } from "vue";
let app: Application<ICanvas>;
onMounted(() => {
  app = new Application({
    width: 600,
    height: 700,
  });
  const view = app.view;
  document.getElementById("main")?.appendChild(view as HTMLCanvasElement);
  // Almanac_GroundDay();
  createMap();
  setTimeout(() => {
    createMyPlane();
  }, 1000);
});

/**
 * 创建我方飞机
 *
 */
async function createMyPlane() {
  // 创建加载器
  const myPlane = await Assets.load("/images/my-plane.png");
  const shotRes = await Assets.load("/images/shot.jpg");
  const plane = new Sprite(myPlane);

  plane.width = 30;
  plane.height = 30;
  // 随机从上方移动到某个位置
  plane.position.set(app.screen.width / 2, app.screen.height - 50);
  app.stage.addChildAt(plane, 1);

  // 给sprite监听鼠标移动事件
  plane.interactive = true;
  // 监听mousemove事件
  let isEdge = false;
  app.view.addEventListener("mousemove", (event) => {
    if (event instanceof MouseEvent) {
      // 更新精灵图的位置为鼠标的当前位置
      if (event.clientX >= app.screen.width) {
        plane.position.x = app.screen.width - 30;
        isEdge = true;
      }
      if (event.clientX <= 0) {
        plane.position.x = 10;
        isEdge = true;
      }
      if (event.clientY >= app.screen.height) {
        plane.position.y = app.screen.height - 10;
        isEdge = true;
      }
      if (event.clientY <= 0) {
        plane.position.y = 10;
        isEdge = true;
      }

      if (
        event.clientX <= app.screen.width &&
        event.clientY <= app.screen.height
      ) {
        isEdge = false;
      }

      if (isEdge) {
        return;
      }
      plane.position.x = event.clientX;
      plane.position.y = event.clientY;
    }
  });

  // 图片闪烁
  function blink() {
    plane.visible = !plane.visible;
  }
  // 发射子弹
  function fire() {
    const shot = new Sprite(shotRes);
    shot.width = 10;
    shot.height = 10;
    shot.position.set(plane.x, plane.y - 10);
    app.stage.addChildAt(shot, 2);

    /**
     * 子弹移动
     */
    const moveShot = () => {
      shot.y -= 10;
      if (shot.y <= 0) {
        app.stage.removeChild(shot);
        app.ticker.remove(moveShot);
      }
    };
    app.ticker.add(moveShot);
  }

  /**
   * 每隔200ms发射一颗子弹
   */
  setInterval(() => {
    fire();
  }, 50);
  app.ticker.add(blink);
}

/**
 * 地图渲染
 */
async function createMap() {
  const mapTexture = await Assets.load("/images/bg.jpg");
  const sprite = new Sprite(mapTexture);
  app.stage.addChild(sprite);
}
</script>

<style scoped>
#main {
  cursor: none !important;
}
</style>
